<!--eslint-disable-->
<template>
    <div class="dropdown" ref="dropdownRef">
        <!--        <router-link to="/login" class="btn btn-outline-light my-2 dropdown-toggle">
                    {{ title }}
                </router-link>-->
        <a @click.prevent="toggleOpen" href="#" class="btn btn-outline-light my-2 dropdown-toggle">
            {{ title }}
        </a>
        <ul class="dropdown-menu" :style="{display:'block'}" v-if="isOpen">
            <slot></slot>
        </ul>
    </div>
</template>

<script setup lang="ts">
import {ref, toRefs, watch} from "vue";
import useClickOutside from "@/hooks/useClickOutside";

const props = defineProps({
    title: {
        type: String,
        required: true
    }
})
const {title} = toRefs(props)
const isOpen = ref(false)

//dropdownRef dom对象，类型可能为null或者html dom类型，所以泛型插传入null | HTMLInputElement
const dropdownRef = ref<null | HTMLInputElement>(null)

//切换dropdown
const toggleOpen = () => {
    isOpen.value = !isOpen.value
}

// 使用点击钩子函数，传入dropdownRef，用于判断dropdown dom是否包含被点击的dom。
// 如果dropdown打开时，并且点击的位置不是dropdown，就关闭dropdown
const isClickOutside = useClickOutside(dropdownRef)

//监听每次点击
watch(isClickOutside, () => {
    // 如果dropdown打开并且点击的位置不是dropdown，就关闭dropdown
    if (isOpen.value && isClickOutside.value) {
        isOpen.value = false
    }
})

/*const handle = (e: MouseEvent) => {
    if (dropdownRef.value) {
        if (!dropdownRef.value.contains(e.target as HTMLInputElement) && isOpen.value) {
            isOpen.value = false
        }
    }
}

onMounted(() => {
    document.addEventListener('click', handle)
})

onUnmounted(() => {
    document.removeEventListener('click', handle)
})*/
</script>

<style scoped>

</style>